<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<title>HTML5 WebSocket测试</title>
</head>

<body>
	<div>
		<input type="button" value="Login" onclick="login()" />
		<input type="button" value="Logout" onclick="logout()" />
		<input type="button" value="Chat" onclick="Chat()" />
	</div>
	<div id="messages"></div>
	<script type="text/javascript">
		var global_count = 10000;
		var webSocket = new WebSocket('ws://127.0.0.1:2020');
		webSocket.onerror = function (event) {
			alert(event.data);
		};
		//与WebSocket建立连接
		webSocket.onopen = function (event) {
			document.getElementById('messages').innerHTML = '与服务器端建立连接';
		};
		//处理服务器返回的信息
		webSocket.onmessage = function (event) {
			document.getElementById('messages').innerHTML += '<br />' + event.data;
		};

		function Chat() {
			//向服务器发送请求
			var obj = {
				"method": "aichatReq",
				"appid": "1.00002",
				"content": "你好"
			};
			webSocket.send(JSON.stringify(obj));
		}

		function login() {
			var obj = {
				"method": "loginReq",
				"serviceId": 161,
				"appid": "1.00002",
				"uname": "hxw002"
			}
			webSocket.send(JSON.stringify(obj));
		}
		function logout() {
			var obj = {
				"method": "logoutReq",
				"appid": "1.00002"
			};
			webSocket.send(JSON.stringify(obj));
		}
	</script>
</body>

</html>